$(function(){

    $(".pay-weixin").click(function () {
        $payQrcode = $(".weixin_pay_qr_code");

        if($payQrcode.css("display") == "none"){
            getQrcode();
        }else if($payQrcode.css("display") == "block"){
            $payQrcode.css("display", "none");
            if (timer) {
                clearTimeout(timer);
                timer = 0;
            }
        }else{
            getQrcode();
        }
        
        return false;
    })


    $(".pay-ali").click(function () {
        $url = $(".ali_pay_url").val();
        checkPayment();
        window.open($url);
    })


    function getQrcode(){
        var getCodeUrl = $(".wx_qrcode_get_url").val();
        $.ajax({
            url: getCodeUrl,
            dataType: 'json',
            type: 'get',
            success: function(json){
                if(json.status > 0){
                    if(json.wxPayUrl == null){
                        alert("本次获取失败，请点击微信支付重新获取~");
                    }else{
                        drawQrcode(json.wxPayUrl);
                        $(".weixin_pay_qr_code").css("display", "block");
                    }
                }else{
                    location.href = "/login";
                }
            },
            error: function(e){
                alert("获取二维码失败，请刷新页面重新获取");
                return false;
            }
        })
    }

    function drawQrcode(wxPayUrl){
        var $weixinPayQrcode = $('.weixin_pay_qr_code');

        $weixinPayQrcode.html('');
        $('.weixin_pay_qr_code').qrcode({
            render: "canvas",
            text: wxPayUrl,
            width: 146,
            height: 146
        });
        
        checkPayment();
    }
    
    var paymentCheckUrl = $(".wx_payment_get_url").val();
    var timer = 0;
    function checkPayment() {
        $.get(paymentCheckUrl+"?t=" + new Date().getTime(), function (json) {
            if (json.success == true) {
                  alert("恭喜您成功购买课程")
                  location.reload();
            } else {
            	timer = setTimeout(checkPayment, 3000);
            }
        });
    }
});
